﻿using System;
using Dndz.Industries.Models;
using Dndz.Industries.Services;
using Dndz.Industries.Settings;
using Orchard.ContentManagement.Drivers;
using Orchard.Mvc;

namespace Dndz.Industries.Drivers
{
    public class CaptchaPartDriver : ContentPartDriver<CaptchaPart>
    {
        private readonly ICaptchaService _captchaService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CaptchaPartDriver(ICaptchaService captchaService, IHttpContextAccessor httpContextAccessor)
        {
            _captchaService = captchaService;
            _httpContextAccessor = httpContextAccessor;
        }

        protected override DriverResult Display(CaptchaPart part, string displayType, dynamic shapeHelper)
        {
            var settings = part.Settings.GetModel<CaptchaTypePartSettings>();

            return ContentShape("Parts_Captcha", () =>
            {
                var result = shapeHelper.Parts_Captcha(ContentPart: part,
                    DefContentItemFieldName: CaptchaServiceConstants.CAPTCHA_DEFAULT_CONTENTITEM_FIELD_NAME);

                if (!settings.IsForNotAuthUsersOnly || !_httpContextAccessor.Current().Request.IsAuthenticated)
                {
                    // Pick a GUID to represent this challenge
                    var newGuid = Guid.NewGuid().ToString();
                    result.Guid = newGuid;
                    result.ImgSrc = _captchaService.GenerateCaptcha(part.ContentItem.ContentType, newGuid, settings);
                    result.DefTextBoxName = CaptchaServiceConstants.CAPTCHA_DEFAULT_TEXTBOX_NAME;
                    result.DefGuidFieldName = CaptchaServiceConstants.CAPTCHA_DEFAULT_GUID_FIELD_NAME;
                }

                return result;
            });
        }
    }
}
